package com.project.personnel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.personnel.entity.Hr;
import com.project.personnel.service.HrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

//登录
@RestController
@RequestMapping("/login")
public class LoginController {
    @Resource
    private HrService hrService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    @Resource
    private KaptchaController kaptchaController;

    @PostMapping("/login")
    public Object toLogin(HttpSession session, Hr hr) {
        Map<String, String> map = new HashMap<>();
        QueryWrapper<Hr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", hr.getUsername());
        Hr hrOne = hrService.getOne(queryWrapper);
        if (hrOne == null) {
            map.put("state", "用户名不存在");
            return map;
        }else{
            if (!passwordEncoder.matches(hr.getPassword(), hrOne.getPassword())) {
                map.put("state", "密码输入错误");
                return map;
            }else{
                String kaptchaCode = kaptchaController.getCheckCode();//生成的码
                String code = hr.getCheck();
                if (!kaptchaCode.equals(code)){
                    map.put("state", "验证码请与图片一致");
                    return map;
                }
            }
        }
        map.put("state", "success");
        session.setAttribute("HrOne",hrOne);
        return map;
    }

}
